from user.models import User
from user.serializers import UserInfoSerializer
from utils import custom_exceptions as cex
from utils.tools import is_valid_account, is_valid_password


class UserService:
	def __init__(self):
		self.user_set = User.objects.get_queryset()
		self.serializer = UserInfoSerializer
		
	def user_login(self, username, password):
		if not is_valid_account(username) or not is_valid_password(password):
			raise cex.AccountPasswordErrorException()
		if user_model:= self.user_set.filter(username=username):
			if user_model[0].verify(password):
				return self.serializer(user_model[0]).data
			else: raise cex.LoginErrorException()
		else: raise cex.UserNotExistsErrorException()
		
	def user_register(self, username, password, nickname):
		if not is_valid_account(username) or not is_valid_password(password):
			raise cex.AccountPasswordErrorException()
		if self.user_set.filter(username=username):
			raise cex.UserDuplicateErrorException()
		else:
			new_user = User(username=username, password=password, nickname=nickname)
			new_user.create()
			return self.serializer(new_user).data
		
	def get_user(self, uid):
		if user_model:= self.user_set.filter(uid=uid):
			return self.serializer(user_model[0]).data
		else:
			raise cex.UserNotExistsErrorException()
		
	def user_avatar(self, uid, avatar):
		user_model = self.user_set.get(uid=uid)
		new_avatar = user_model.update_avatar(avatar)
		return new_avatar
